package main

import (
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"time"
)

var EtcdClient *clientv3.Client

func runEtcdDemo() {
	NewEtcdCli()
	grant()
}

/*
初始话 etcd 客户端
*/
func NewEtcdCli() *clientv3.Client {
	var err error
	EtcdClient, err = clientv3.New(clientv3.Config{
		Endpoints:            []string{"127.0.0.1:2379"},
		AutoSyncInterval:     time.Minute,
		DialTimeout:          5 * time.Second,
		DialKeepAliveTime:    1 * time.Second,
		DialKeepAliveTimeout: 5 * time.Second,
		RejectOldCluster:     true,
	})
	if err != nil {
		fmt.Println("new ectd client err:%v", err)
	}
	return EtcdClient
}

//申请租约 & 设置key值
func grant() {
	//申请租约 有效10s
	resp, err := EtcdClient.Grant(EtcdClient.Ctx(), 10)

	if err != nil {
		fmt.Printf("grant err:%v \n", err)
	}
	//租约id
	lease := resp.ID
	fmt.Printf("grant租约完成 租约id %v ttl 10s\n", lease)

	//设置key 值
	res, err := EtcdClient.Put(EtcdClient.Ctx(), "test/etcd", "tesss", clientv3.WithLease(lease))
	fmt.Printf("设置key值 结果 %v,err:%v \n", res, err)

	//获取key值
	getres, err := EtcdClient.Get(EtcdClient.Ctx(), "test/etcd")
	fmt.Printf("获取key值 结果 %v,err:%v \n", getres, err)

	//续租
	keepAliveAsync(lease)

	fmt.Printf("休眠20s...")
	time.Sleep(20 * time.Second)
	getres, err = EtcdClient.Get(EtcdClient.Ctx(), "test/etcd")
	fmt.Printf("休眠20s后， 获取key值 结果 %v,err:%v \n", getres, err)

}

//续约
func keepAliveAsync(leaseId clientv3.LeaseID) {
	ch, err := EtcdClient.KeepAlive(EtcdClient.Ctx(), leaseId)
	if err != nil {
		fmt.Printf("续约错误 %v", err)
	}

	for {
		select {
		case res, ok := <-ch:
			fmt.Printf("续租 %v, %v \n", res, ok)
		}
	}

	//.KeepAlive()
}

//reference
//https://blog.csdn.net/u010278923/article/details/71727682
